package com.alpha.task.job;

import org.apache.log4j.Logger;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.stereotype.Component;

import com.alpha.core.tools.RestTemplateTool;
import com.alpha.mybaits.mapper.TcSystemConfigMapper;
import com.alpha.mybaits.mapper.TcTaskInfoMapper;
import com.alpha.mybaits.model.TcSystemConfig;
import com.alpha.mybaits.model.TcTaskInfo;
import com.alpha.task.constant.CountDownConstant;


@Component
public class CountDownJob extends QuartzJobBean{
	
	protected Logger logger =  Logger.getLogger(getClass().getName());
	
	
	@Override
	protected void executeInternal(JobExecutionContext arg0) throws JobExecutionException {
		logger.info("CountDownJob  to executeInternal  Task ======>>>");
		TcTaskInfo task = (TcTaskInfo) arg0.getJobDetail().getJobDataMap().get(CountDownConstant.TASK_JOB_OBJECT);
		
		
		if(task != null){
			
			TcSystemConfigMapper configMapper =(TcSystemConfigMapper) arg0.getJobDetail().getJobDataMap().get(CountDownConstant.TASK_INFO_SYSTEM_CONFIG);
			
			TcTaskInfoMapper taskInfoMapper = (TcTaskInfoMapper) arg0.getJobDetail().getJobDataMap().get(CountDownConstant.TASK_INFO_MAPPER);
			
			TcSystemConfig configSelt = new TcSystemConfig();
			
			configSelt.setStatus(TcSystemConfig.USING);
			configSelt.setName(task.getTaskProjectPlatform());
			configSelt.setType("internal_url");
			
			TcSystemConfig cfg = configMapper.selectOne(configSelt);
			
			if(cfg == null){
				logger.info("task config is error : task id = " + task.getId());
				return;
			}
			
			String targetUrl = cfg.getContent() + task.getTaskInterface();
			String param = task.getTaskProjectParam();
			
			if(param != null && !param.trim().isEmpty()){
				targetUrl += param;
				
			}
			
			logger.info("CountDownJob Task Target URL :" + targetUrl);
			logger.info("model name :" + task.getTaskModelName());
			logger.info("begin time :" + task.getTaskDate());
			logger.info("task param  :" + param);
			
			task.setStatus(TcTaskInfo.HAD_TRIGGER);
			try {
				RestTemplateTool.getResttemplate().put(targetUrl, null);
			} catch (Exception e) {
				e.printStackTrace();
				task.setStatus(TcTaskInfo.DEFEAT_TRIGGER);
			}
		
			
			
			taskInfoMapper.updateByPrimaryKeySelective(task);
		}
		
		
		logger.info("CountDownJob task end  <<<=======");
	}

}
